package com.tiptop.mybatis.util;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MySqlSession {
	private static SqlSessionFactory factory = null;
	private static SqlSession sqlSession = null;
	
	static{
		try {
			// 读取属性文件a.properties,加载属性列表
			//Properties properties =	Resources.getResourceAsProperties("jdbc.properties");
			//加载mybatis配置文件和映射文件
			Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			//factory = builder.build(reader, properties);
			factory = builder.build(reader);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 获取SqlSession
	 * 
	 * @return
	 */
	public static SqlSession getSession() {
		if (sqlSession == null) {
			sqlSession = factory.openSession();
		}
		return sqlSession;
	}

	/**
	 * 从配置文件中获取数据库表映射对象信息
	 * 
	 * @param mapper
	 * @return
	 */
	public static <T> T getMapper(Class<T> mapper) {
		SqlSession session = getSession();
		return (T) session.getMapper(mapper);
	}

	/**
	 * 数据提交
	 */
	public static void commit() {
		sqlSession.commit();
	}

	/**
	 * 数据回滚
	 */
	public static void rollback() {
		sqlSession.rollback();
	}

	/**
	 * 关闭sqlsession
	 */
	public static void close() {
		if (sqlSession != null) {
			sqlSession.close();
		}
	}
}
